import {Injectable} from '@angular/core';
import {CanActivate, CanActivateChild, Router, ActivatedRouteSnapshot, RouterStateSnapshot} from "@angular/router";
import {ToolsService} from "@shared/service/tools/tools.service";
import {AuthService} from "@shared/service/auth/auth.service";

@Injectable()
export class AuthGuardService implements CanActivate, CanActivateChild {

  constructor(
    public router: Router,
    public tools: ToolsService,
    public authService: AuthService
  ) {
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    const url = state.url;
    return this.checkLogin(url);
  }

  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return this.canActivate(route, state);
  }

  checkLogin(url: string): boolean {
    if (this.authService.isLoggedIn) {
      return true;
    }
    // this.tools.presentConfirm('此操作需要登录,是否前往登录',1,this.goToLogin.bind(this));
    this.authService.logout();
    this.authService.redirectUrl = url;
    this.authService.selectGoToLogin();
    return false;
  }

}
